﻿using System.Text;

namespace CxExtension.System
{
	public class BitConverterE
	{

		static readonly StringBuilder sBuilder = new StringBuilder();
		static readonly StringBuilder Result = new StringBuilder();
		const string HexAlphabet = "0123456789ABCDEF";

		public static string ToHexString(byte[] bytes, int start, int count)
		{
			Result.Clear();
			var leng = start + count;

			for (var i = start; i < leng; i++)
			{
				byte B = bytes[i];
				Result.Append(HexAlphabet[(int) (B >> 4)]);
				Result.Append(HexAlphabet[(int) (B & 0xF)]);
			}
			return Result.ToString();
		}

		public static byte[] HexStringToByteArray(string Hex)
		{
			byte[] Bytes = new byte[Hex.Length / 2];
			int[] HexValue = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
				0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

			for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1)
			{
				Bytes[x] = (byte)(HexValue[char.ToUpper(Hex[i + 0]) - '0'] << 4 |
								  HexValue[char.ToUpper(Hex[i + 1]) - '0']);
			}

			return Bytes;
		}

		public static string ToHashStr(byte[] data, int start,int count)
		{
			return ToHexString(data, start, count);
		}

		public static string ToHashStr(byte[] data)
		{
			return ToHashStr(data, 0, data.Length);
		}
	}
}
